package com.geo.content.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.geo.content.dto.ContentGenerationRequest;
import com.geo.content.dto.ContentGenerationResponse;
import com.geo.content.dto.ContentListResponse;
import com.geo.content.entity.MediaFile;
import com.geo.content.entity.MultimodalContent;
import com.geo.content.service.ContentGenerationService;
import com.geo.content.service.ContentService;
import com.geo.content.service.FileUploadService;
import com.geo.common.result.Result;
import com.geo.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.List;

/**
 * 内容管理API控制器
 * 
 * @author GEO Team
 * @version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/api/content")
@Validated
public class ContentController {
    
    private static final Logger logger = LoggerFactory.getLogger(ContentController.class);
    
    @Autowired
    private ContentService contentService;
    
    @Autowired
    private ContentGenerationService contentGenerationService;
    
    @Autowired
    private FileUploadService fileUploadService;
    
    /**
     * 生成内容
     * @param request 内容生成请求
     * @return 生成结果
     */
    @PostMapping("/generate")
    public Result<ContentGenerationResponse> generateContent(@Valid @RequestBody ContentGenerationRequest request) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            request.setMerchantId(merchantId);
            
            ContentGenerationResponse response = contentGenerationService.generateContent(request);
            
            logger.info("内容生成成功: {}", request.getTitle());
            return Result.success(response);
            
        } catch (Exception e) {
            logger.error("内容生成失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 批量生成内容
     * @param requests 内容生成请求列表
     * @return 生成结果列表
     */
    @PostMapping("/batch-generate")
    public Result<List<ContentGenerationResponse>> batchGenerateContent(@Valid @RequestBody List<ContentGenerationRequest> requests) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            // 设置商家ID
            requests.forEach(request -> request.setMerchantId(merchantId));
            
            List<ContentGenerationResponse> responses = contentGenerationService.batchGenerateContent(requests);
            
            logger.info("批量内容生成完成: {} 个内容", requests.size());
            return Result.success(responses);
            
        } catch (Exception e) {
            logger.error("批量内容生成失败", e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 优化内容
     * @param contentId 内容ID
     * @param optimizationType 优化类型
     * @return 优化结果
     */
    @PostMapping("/{contentId}/optimize")
    public Result<MultimodalContent> optimizeContent(@PathVariable String contentId,
                                                            @RequestParam String optimizationType) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            MultimodalContent response = contentGenerationService.optimizeContent(contentId, optimizationType, merchantId);
            
            logger.info("内容优化成功: {} - {}", contentId, optimizationType);
            return Result.success(response);
            
        } catch (Exception e) {
            logger.error("内容优化失败: {}", contentId, e);
            return Result.error(ResultCode.AI_API_ERROR, e.getMessage());
        }
    }
    
    /**
     * 获取内容列表
     * @param page 页码
     * @param size 页大小
     * @param status 状态筛选
     * @param contentType 内容类型筛选
     * @param keyword 关键词筛选
     * @return 内容列表
     */
    @GetMapping
    public Result<ContentListResponse> getContentList(@RequestParam(defaultValue = "1") int page,
                                                     @RequestParam(defaultValue = "10") int size,
                                                     @RequestParam(required = false) String status,
                                                     @RequestParam(required = false) String contentType,
                                                     @RequestParam(required = false) String keyword) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            ContentListResponse response = contentService.getContentList(merchantId, page, size, status, contentType, keyword);
            
            return Result.success(response);
            
        } catch (Exception e) {
            logger.error("获取内容列表失败", e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 获取内容详情
     * @param contentId 内容ID
     * @return 内容详情
     */
    @GetMapping("/{contentId}")
    public Result<MultimodalContent> getContentDetail(@PathVariable String contentId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            MultimodalContent content = contentService.getContentDetail(contentId, merchantId);
            
            return Result.success(content);
            
        } catch (Exception e) {
            logger.error("获取内容详情失败: {}", contentId, e);
            return Result.error(ResultCode.CONTENT_NOT_FOUND, e.getMessage());
        }
    }
    
    /**
     * 更新内容
     * @param contentId 内容ID
     * @param content 内容更新数据
     * @return 更新结果
     */
    @PutMapping("/{contentId}")
    public Result<MultimodalContent> updateContent(@PathVariable String contentId,
                                                  @Valid @RequestBody MultimodalContent content) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            MultimodalContent updatedContent = contentService.updateContent(contentId, content, merchantId);
            
            logger.info("内容更新成功: {}", contentId);
            return Result.success(updatedContent);
            
        } catch (Exception e) {
            logger.error("内容更新失败: {}", contentId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 删除内容
     * @param contentId 内容ID
     * @return 删除结果
     */
    @DeleteMapping("/{contentId}")
    public Result<String> deleteContent(@PathVariable String contentId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            contentService.deleteContent(contentId, merchantId);
            
            logger.info("内容删除成功: {}", contentId);
            return Result.success("删除成功");
            
        } catch (Exception e) {
            logger.error("内容删除失败: {}", contentId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 发布内容
     * @param contentId 内容ID
     * @param platforms 发布平台列表
     * @return 发布结果
     */
    @PostMapping("/{contentId}/publish")
    public Result<String> publishContent(@PathVariable String contentId,
                                        @RequestParam List<String> platforms) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            contentService.publishContent(contentId, platforms, merchantId);
            
            logger.info("内容发布成功: {} -> {}", contentId, platforms);
            return Result.success("发布成功");
            
        } catch (Exception e) {
            logger.error("内容发布失败: {}", contentId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 上传文件
     * @param file 文件
     * @param contentId 关联的内容ID（可选）
     * @param description 文件描述
     * @return 文件信息
     */
    @PostMapping("/upload")
    public Result<MediaFile> uploadFile(@RequestParam("file") MultipartFile file,
                                       @RequestParam(required = false) String contentId,
                                       @RequestParam(required = false) String description) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            MediaFile mediaFile = fileUploadService.uploadFile(file, merchantId, contentId, description);
            
            logger.info("文件上传成功: {}", file.getOriginalFilename());
            return Result.success(mediaFile);
            
        } catch (Exception e) {
            logger.error("文件上传失败", e);
            return Result.error(ResultCode.FILE_UPLOAD_FAILED, e.getMessage());
        }
    }
    
    /**
     * 批量上传文件
     * @param files 文件列表
     * @param contentId 关联的内容ID（可选）
     * @return 文件信息列表
     */
    @PostMapping("/batch-upload")
    public Result<List<MediaFile>> batchUploadFiles(@RequestParam("files") List<MultipartFile> files,
                                                   @RequestParam(required = false) String contentId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            List<MediaFile> mediaFiles = fileUploadService.uploadFiles(files, merchantId, contentId);
            
            logger.info("批量文件上传成功: {} 个文件", files.size());
            return Result.success(mediaFiles);
            
        } catch (Exception e) {
            logger.error("批量文件上传失败", e);
            return Result.error(ResultCode.FILE_UPLOAD_FAILED, e.getMessage());
        }
    }
    
    /**
     * 获取文件信息
     * @param fileId 文件ID
     * @return 文件信息
     */
    @GetMapping("/files/{fileId}")
    public Result<MediaFile> getFileInfo(@PathVariable String fileId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            MediaFile mediaFile = fileUploadService.getFileInfo(fileId, merchantId);
            
            return Result.success(mediaFile);
            
        } catch (Exception e) {
            logger.error("获取文件信息失败: {}", fileId, e);
            return Result.error(ResultCode.FILE_NOT_FOUND, e.getMessage());
        }
    }
    
    /**
     * 删除文件
     * @param fileId 文件ID
     * @return 删除结果
     */
    @DeleteMapping("/files/{fileId}")
    public Result<String> deleteFile(@PathVariable String fileId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            fileUploadService.deleteFile(fileId, merchantId);
            
            logger.info("文件删除成功: {}", fileId);
            return Result.success("删除成功");
            
        } catch (Exception e) {
            logger.error("文件删除失败: {}", fileId, e);
            return Result.error(ResultCode.FILE_DELETE_FAILED, e.getMessage());
        }
    }
    
    /**
     * 获取内容版本历史
     * @param contentId 内容ID
     * @return 版本历史
     */
    @GetMapping("/{contentId}/versions")
    public Result<List<MultimodalContent>> getContentVersions(@PathVariable String contentId) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            List<MultimodalContent> versions = contentService.getContentVersions(contentId, merchantId);
            
            return Result.success(versions);
            
        } catch (Exception e) {
            logger.error("获取内容版本历史失败: {}", contentId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
    
    /**
     * 内容审核
     * @param contentId 内容ID
     * @param action 审核动作（approve/reject）
     * @param reason 审核原因
     * @return 审核结果
     */
    @PostMapping("/{contentId}/review")
    public Result<String> reviewContent(@PathVariable String contentId,
                                       @RequestParam String action,
                                       @RequestParam(required = false) String reason) {
        try {
            String merchantId = StpUtil.getLoginIdAsString();
            
            contentService.reviewContent(contentId, action, reason, merchantId);
            
            logger.info("内容审核完成: {} - {}", contentId, action);
            return Result.success("审核完成");
            
        } catch (Exception e) {
            logger.error("内容审核失败: {}", contentId, e);
            return Result.error(ResultCode.FAILURE, e.getMessage());
        }
    }
}